package com.aaron.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.patchca.random.RandUtils;
import org.patchca.service.AbstractCaptchaService;
import org.patchca.utils.encoder.EncoderHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.aaron.captcha.service.ChineseRandomCaptchaService;
import com.aaron.captcha.service.LettersAndNumCaptchaService;

/**
 * 图形验证码
 * 
 * @author aaron
 * @varsion 0.1.0 2017年11月12日
 */
@RestController
public class ImageCodeController {
	/** 含中文语义分析验证码 */
	private static final ChineseRandomCaptchaService	crcs	= new ChineseRandomCaptchaService();
	/** 常规英文识别验证码 */
	private static final LettersAndNumCaptchaService	lncs	= new LettersAndNumCaptchaService();

	@RequestMapping("/pcrimg")
	public void crimg(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession(false);
		if (session == null) {
			session = request.getSession();
		}
		setResponseHeaders(response);
		AbstractCaptchaService cs;
		int random = RandUtils.randInt(100);
		// 70%概率使用常规验证码
		if (random< 70) {
			cs = lncs;
		} else {
			cs = crcs;
		}

		String token = EncoderHelper.getChallangeAndWriteImage(cs, "png", response.getOutputStream());
		session.setAttribute("captchaToken", token);
		System.out.println("当前的SessionID=" + session.getId() + "，验证码=" + token);
	}

	protected void setResponseHeaders(HttpServletResponse response) {
		response.setContentType("image/png");
		response.setHeader("Cache-Control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		long time = System.currentTimeMillis();
		response.setDateHeader("Last-Modified", time);
		response.setDateHeader("Date", time);
		response.setDateHeader("Expires", time);
	}
}
